const router = require('koa-router')();
const GoodsListScheme = require('../db/schema/goods');
const UserScheme = require('../db/schema/user');

router.post('/', async (ctx, next) => {
  // 订单信息
  const r1 = Math.floor(Math.random() * 10);
  const r2 = Math.floor(Math.random() * 10);    
  const createDate = (new Date()).valueOf();
  const orderId = r1 + createDate + r2;
  const data = ctx.request.body
  const username = ctx.session.username
  let newData = []
  const order = await UserScheme.findOne({ username })
  if (!order.order) {
    order.order = {}
  }
  // 根据id查询出购物车订单
  for (let i = 0; i < data.orderId.length; i++) {
    if (data.idDirect) {
      const res = await GoodsListScheme.findOne({ id: data.orderId[0] })
      newData[i] = {
        order_id: orderId + i,
        count: data.count,
        present_price: res.present_price,
        id: res.id,
        image_path: res.image_path,
        name: res.namem,
        mallPrice: data.totalPrice,
      }
    } else {
      let item = await UserScheme.aggregate([{ "$unwind": "$shopList" },
      { "$match": { "shopList.id": data.orderId[i], username } },
      { "$project": { "shopList": 1 } }])
      newData[i] = item[0].shopList
      newData[i].order_id = orderId + i
    }

  }
  if (!order.order[orderId]) {
    order.order[orderId] = {
      address: data.address,
      tel: data.tel,
      orderList: newData,
      totalPrice: data.totalPrice,
      createDate,
      orderId,
    }
  }
  await UserScheme.update({ username }, {
    $set: {
      'order': order.order,
    }
  })

  for (let i = 0; i < data.orderId.length; i++) {
    await UserScheme.findOneAndUpdate({ username, 'shopList.id': data.orderId[i] }, {
      $pull: {
        'shopList': {
          'id': data.orderId[i]
        }
      }
    })
  }
  ctx.body = {
    status: 200,
    msg: '结算成功!'
  }
})

router.post('/addShop', async (ctx, next) => {
  if (!ctx.request.body.id) {
    ctx.body = {
      code: -1,
      msg: '缺少参数id'
    }
    return
  }
  const username = ctx.session.username
  // 单价 id image_path 商品名字
  // 先查数据库有没有这条商品,有就数量加1,没有就新创建一条
  const test = await UserScheme.aggregate([{ "$unwind": "$shopList" },
  { "$match": { "shopList.id": ctx.request.body.id, username } },
  { "$project": { "shopList": 1 } }])
  let newData = test.length && test[0].shopList
  console.log(newData);

  if (newData) {
    await UserScheme.findOneAndUpdate({ username, 'shopList.id': ctx.request.body.id }, {
      $set: {
        'shopList.$.count': newData.count += 1
      }
    })
  } else {  // 说明没有这条数据
    // 查到这条商品数据
    let goods = await GoodsListScheme.findOne({ id: ctx.request.body.id }).exec()
    const { present_price, id, image_path, name } = goods
    let shop = {
      present_price,
      id,
      image_path,
      name,
      mallPrice: present_price,
      check: false,
      count: 1,
    }
    await UserScheme.findOneAndUpdate({ username }, {
      $push: {
        'shopList': shop
      }
    })
  }
  ctx.body = {
    status: 200,
    msg: '加入购物车成功'
  }
})

// 查询购物车
router.get('/getCard', async (ctx, next) => {
  const username = ctx.session.username
  if (!username) {
    ctx.body = {
      status: -1,
      msg: '请登录'
    }
    return
  }
  const res = await UserScheme.findOne({ username })
  ctx.body = {
    status: 200,
    shopList: res && res.shopList || []
  }
})

// 购物车增加和减少
router.post('/editCart', async (ctx, next) => {
  const { count, id, mallPrice } = ctx.request.body
  const username = ctx.session.username
  await UserScheme.findOneAndUpdate({ username, 'shopList.id': id }, {
    $set: {
      'shopList.$.count': count,
      'shopList.$.mallPrice': mallPrice,
    }
  })
  ctx.body = {
    status: 200,
    msg: '修改成功'
  }
})

// 购物车的删除
router.post('/deleteShop', async (ctx, next) => {
  let id = ctx.request.body
  id.forEach(ids => {
    UserScheme.findOneAndUpdate({ username: ctx.session.username, 'shopList.id': ids }, {
      $pull: {
        'shopList': {
          'id': ids
        }
      }
    }).exec()
  })
  ctx.body = {
    status: 200,
    msg: '删除成功'
  }
})

// 查询用户完成订单
router.get('/myOrder', async (ctx, next) => {
  const res = await UserScheme.findOne({ username: ctx.session.username })
  ctx.body = {
    status: 200,
    list: res.order
  }
})

module.exports = router.routes();